<template>
  <div style="padding: 20px">
    <!-- 停供审批 -->
    <a-card :bordered="false" style="height: 800px">
      <a-form layout="inline" :model="formState" ref="formRef">
        <div style="display: flex">
          <a-form-item label="申请时间" name="apply">
            <a-range-picker
              allowClear
              v-model:value="formState.apply"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item label="审批时间" name="approval">
            <a-range-picker
              allowClear
              v-model:value="formState.approval"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item label="审批人" name="approver">
            <a-tree-select
              v-model:value="formState.approver"
              show-search
              style="width: 320px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择审批人"
              allow-clear
              tree-default-expand-all
              :tree-data="treeDataId"
              tree-node-filter-prop="label"
              @change="onChange"
            >
              <template #title="{ value: val, label }">
                <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                <template v-else>{{ label }}</template>
              </template>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="审批状态" name="approvalStatus">
            <a-select
              allowClear
              v-model:value="formState.approvalStatus"
              placeholder="请选择"
              style="width: 200px"
              autocomplete="off"
            >
              <a-select-option value="审核中">审核中</a-select-option>
              <a-select-option value="同意">同意</a-select-option>
              <a-select-option value="拒绝">拒绝</a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <div style="display: flex; margin-top: 20px">
          <a-form-item label="小区" name="villageId">
            <a-tree-select
              v-model:value="formState.villageId"
              show-search
              style="width: 320px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择小区"
              allow-clear
              tree-default-expand-all
              :tree-data="treeVillage"
              tree-node-filter-prop="label"
              @change="onChangeVillage"
            >
              <template #title="{ value: val, label }">
                <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                <template v-else>{{ label }}</template>
              </template>
            </a-tree-select>
            <!-- <a-input
              v-model:value="formState.villageId"
              placeholder="请输入小区"
              autocomplete="off"
              allowClear
            /> -->
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click.prevent="onSubmit">查询</a-button>
            <a-button style="margin-left: 10px" @click="resetForm"
              >重置</a-button
            >
          </a-form-item>
        </div>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        size="middle"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 3000, y: 550 }"
        style="margin-top: 20px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'active'">
            <a-button
              :disabled="record.approvalStatus != '审核中'"
              type="link"
              @click="onEdit(record, '0')"
            >
              同意
            </a-button>
            <a-button
              :disabled="record.approvalStatus != '审核中'"
              type="link"
              danger
              @click="onEdit(record, '1')"
            >
              拒绝
            </a-button>
          </template>
          <template v-if="column.dataIndex === 'download'">
            <a-button type="link" @click="downloadClick(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 同意 -->
    <a-modal
      v-model:open="isConsentOpen"
      width="1000px"
      title="操作审批"
      @ok="ConsentOk"
    >
      <a-textarea
        v-model:value="TextValue"
        placeholder="请输入审批意见"
        :rows="4"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, toRaw, ref, computed, h } from 'vue';
import {
  getStopApprovaldList,
  stopApprovaldOperation,
  selectCommonId,
  selectCommon,
  personCompanyTree,
  getVillageByComId,
} from '#/api/core/planAudit';
import { message } from 'ant-design-vue';

const formState = reactive({
  apply: [], // 申请时间
  approval: [], // 审批时间
  approver: '', // 审批人
  approvalStatus: '', // 审批状态
  villageId: '', // 小区
});
const treeDataId = ref(); // 审批人树
// 查询和重置
const formRef = ref();
const onSubmit = () => {
  GetData();
  console.log(toRaw(formState));
};
const resetForm = () => {
  formRef.value.resetFields();
};

// 弹窗
interface row {
  id: string;
  redAccountType: string;
  redAccountReason: string;
  feeId: string;
}
const isConsentOpen = ref(false); // 同意弹窗
const TextValue = ref(''); // 审批意见
const ApprovalType = ref(''); // 审批类型
const rowData = ref(<row>{}); // 当前行数据
const onEdit = (data: any, type: string) => {
  console.log(data, type);
  if (type) {
    rowData.value = data;
    isConsentOpen.value = true;
    TextValue.value = '';
    ApprovalType.value = type;
  } else {
    rowData.value = data;
    isConsentOpen.value = true;
    TextValue.value = '';
    ApprovalType.value = type;
  }
};

const ConsentOk = async (e: MouseEvent) => {
  const res = await stopApprovaldOperation({
    id: rowData.value.id, //应收删除审批表id
    approvalOpinion: TextValue.value, //审批意见
    type: ApprovalType.value,
  });
  console.log(res);
  if (res.data.code === 200) {
    message.success(res.data.message || '操作成功');
  } else {
    message.error(res.data.msg || '操作失败');
  }
  GetData();
  isConsentOpen.value = false;
};

// 下载
// const downloadClick = async (data: any) => {
// };

const dataSource = ref();
const columns = ref([
  {
    title: '项目',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },

  {
    title: '联系人',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '联系电话',
    dataIndex: 'holdPhone',
    key: 'holdPhone',
    align: 'center',
  },
  {
    title: '申请',
    dataIndex: 'stopState',
    key: 'stopState',
    align: 'center',
  },

  {
    title: '面积名称',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },

  {
    title: '申请时间',
    dataIndex: 'applicationTime',
    key: 'applicationTime',
    align: 'center',
  },
  {
    title: '审批状态',
    dataIndex: 'approvalStatus',
    key: 'approvalStatus',
    align: 'center',
  },
  {
    title: '审批人',
    dataIndex: 'approverName',
    key: 'approverName',
    align: 'center',
  },
  {
    title: '审批时间',
    dataIndex: 'approvalTime',
    key: 'approvalTime',
    align: 'center',
  },
  {
    title: '审批意见',
    dataIndex: 'approvalOpinion',
    key: 'approvalOpinion',
    align: 'center',
  },
  {
    title: '证件证明',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '证件反面',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '房产证明',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '其他材料',
    dataIndex: '',
    key: '',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
    fixed: 'right',
    width: 180,
  },
]);

// 默认分页
const current = ref(1); // 当前页码
const total = ref(0); // 总条数
const pageSize = ref(10); // 每页条数
// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
}));
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  console.log('分页参数', pag);
  current.value = pag.current;
  pageSize.value = pag.pageSize;
  GetData(); // 获取表格数据
};

// 获取表格数据
const GetData = async () => {
  console.log(formState);
  let res = await getStopApprovaldList({
    approvaldCheckData: {
      applicationTimeBegin:
        formState.apply && formState.apply[0] ? formState.apply[0] : '',
      applicationTimeEnd:
        formState.apply && formState.apply[1] ? formState.apply[1] : '',
      applicantId: '',
      approvalTimeBegin:
        formState.approval && formState.approval[0]
          ? formState.approval[0]
          : '',
      approvalTimeEnd:
        formState.approval && formState.approval[1]
          ? formState.approval[1]
          : '',
      approvalStatus: formState.approvalStatus,
      approverId: formState.approver,
      villageId: formState.villageId,
    },
    page: current.value,
    limit: pageSize.value,
  });
  console.log(res);
  dataSource.value = res.data;
  total.value = res.total;
};
GetData();

// 修改初始化方法获取审批人下拉数据
const getSelectData = async () => {
  let res = await selectCommonId();
  treeDataId.value = res.map((item: any) => ({
    label: item.name,
    value: item.id || item.userId,
  }));
  console.log(treeDataId.value, '初始化');
};
const onChange = async (value: any, node: any) => {
  console.log(value, node, 'onChange');
  const res = await selectCommon(value);
  treeDataId.value = updateChildren(treeDataId.value, value, res); // 递归更新子节点
};
const updateChildren = (
  nodes: any[],
  targetValue: string,
  newChildren: any[],
) => {
  return nodes.map((node) => {
    // 当前节点匹配时添加子节点
    if (node.value === targetValue) {
      return {
        ...node,
        children: newChildren.map((child) => ({
          label: child.name,
          value: child.id || child.userId,
          children: [], // 初始化空children用于继续展开
        })),
      };
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      return {
        ...node,
        children: updateChildren(node.children, targetValue, newChildren),
      };
    }

    return node;
  });
};
getSelectData();
// 初始化小区下拉选
const treeVillage = ref([]);
const onChangeVillage = async (value: any, node: any) => {
  // 判断点击的是最后一级节点
  console.log(value, node, 'onChangeVillage');
  // 判断点击的名字里带公司字
  if (node.toString().includes('公司')) {
    const res = await getVillageByComId(value);
    if (res.data.data.length > 0) {
      // // 递归查找目标节点并更新children
      const updateTree = (nodes, targetValue, newChildren) => {
        return nodes.map((node) => {
          // 如果找到了目标节点，更新其children
          if (node.value === targetValue) {
            return {
              ...node,
              children: newChildren.map((child) => ({
                label: child.comName,
                value: `${targetValue}-${child.comId}`, // 生成唯一复合key
                children: [], // 初始化空children用于继续展开
              })),
            };
          }
          if (node.children && node.children.length > 0) {
            return {
              ...node,
              children: updateTree(node.children, targetValue, newChildren),
            };
          }
          return node;
        });
      };
      treeVillage.value = updateTree(treeVillage.value, value, res.data.data);
      console.log(treeVillage.value, '最终树形结构');
    }
  } else if (value.includes('-')) {
    console.log('小区idididididid', value);
    // formState.villageId = value.split('-')[1];
  }
};
const getSelectVillageData = async () => {
  let res = await personCompanyTree();
  treeVillage.value.push({
    label: res.data.name,
    value: res.data.id,
    children: updateVillageChildren(res.data.children),
  });
};
// 循环更新小区子节点
const updateVillageChildren = (data: any) => {
  if (data && data.length > 0) {
    return data.map((item: any) => ({
      label: item.name,
      value: item.id,
      children: updateVillageChildren(item.children),
    }));
  }
};
getSelectVillageData();
</script>

<style scoped></style>
